<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="产品名称" prop="productName">
        <self-select v-model="queryParams.productId" type="product"  />
      </el-form-item>
      <el-form-item label="产品型号" prop="productModel">
        <el-input
          v-model="queryParams.productModel"
          placeholder="请输入产品型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品单位" prop="productUnit">
        <el-select v-model="queryParams.productUnit" placeholder="请选择产品单位" clearable>
          <el-option
            v-for="dict in dict.type.bus_product_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:inventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:inventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品型号" align="center" prop="productModel" />
      <el-table-column label="产品单位" align="center" prop="productUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_product_unit" :value="scope.row.productUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="当前库存数量" align="center" prop="currentStock" />
      <el-table-column label="采购总额" align="center" prop="purchaseTotal" />
      <el-table-column label="入库时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleInfo(scope.row)"
            v-hasPermi="['inventory:history:add']"
          >添加出入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">


          <el-form-item label="产品名称" prop="productName">
            <self-select v-model="queryParams.productId" type="product" @selectData="getProductData"/>
          </el-form-item>

        <el-form-item label="产品型号" prop="productModel">
          <el-input v-model="form.productModel" placeholder="请输入产品型号" />
        </el-form-item>
        <el-form-item label="产品单位" prop="productUnit">
          <el-select v-model="form.productUnit" placeholder="请选择产品单位">
            <el-option
              v-for="dict in dict.type.bus_product_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看库存对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="80%" append-to-body :close-on-click-modal="false">
        <el-divider content-position="center">库存信息</el-divider>
        <el-descriptions border>
          <el-descriptions-item label="产品名称">{{ form.productName }}</el-descriptions-item>
          <el-descriptions-item label="产品型号">{{ form.productModel }}</el-descriptions-item>
          <el-descriptions-item label="当前库存数量">
            {{ form.currentStock }}
            <dict-tag :options="dict.type.bus_product_unit" :value="form.productUnit"/>
          </el-descriptions-item>
          <el-descriptions-item label="采购总额">{{ form.purchaseTotal }} 元</el-descriptions-item>
          <el-descriptions-item label="入库时间">
            <span>{{ parseTime(form.createTime) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ form.remark }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="center">出入库记录</el-divider>
        <el-table :data="ytInventoryHistoryList" :row-class-name="rowYtInventoryHistoryIndex" @selection-change="handleYtInventoryHistorySelectionChange" ref="ytInventoryHistory">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="关联维修记录" prop="recordId" width="150"></el-table-column>
          <el-table-column label="库存类型" prop="stockType" width="150">
            <template slot-scope="scope">
              <dict-tag :options="scope.row.changeType === 'IN'? dict.type.bus_stock_type_in : dict.type.bus_stock_type_out"/>
            </template>
          </el-table-column>
          <el-table-column label="库存变化类型" prop="changeType" width="150"></el-table-column>
          <el-table-column label="库存变化数量" prop="quantity" width="150"></el-table-column>
          <el-table-column label="更新前数量" prop="beforeQuantity" width="150"></el-table-column>
          <el-table-column label="更新后数量" prop="afterQuantity" width="150"></el-table-column>
          <el-table-column label="金额(元)" prop="amount" width="150"></el-table-column>
          <el-table-column label="出入库日期" prop="transactionDate" width="240">
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.transactionDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择出入库日期" />
            </template>
          </el-table-column>
        </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/inventory/inventory";
import {listProducts} from "@/api/inventory/products";

export default {
  name: "Inventory",
  dicts: ['bus_stock_type_in', 'bus_change_type', 'bus_product_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedYtInventoryHistory: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      inventoryList: [],
      // 产品表格数据
      productsList: [],
      // 出入库记录表格数据
      ytInventoryHistoryList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        productName: null,
        productModel: null,
        productUnit: null,
        currentStock: null,
        purchaseTotal: null,
        stockType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productModel: [
          { required: true, message: "产品型号不能为空", trigger: "blur" }
        ],
        productUnit: [
          { required: true, message: "产品单位不能为空", trigger: "change" }
        ],
      }
      ,

    };
  },
  created() {
    this.getList();
    this.getProductsList();
  },
  methods: {
    /** 查询产品列表 */
    getProductsList() {
      this.loading = true;
      listProducts({pageSize: 10000}).then(response => {
        this.productsList = response.rows;
      });
    },
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: null,
        productId: null,
        productName: null,
        productModel: null,
        productUnit: null,
        currentStock: 0,
        purchaseTotal: 0,
        stockType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.ytInventoryHistoryList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryId = row.inventoryId || this.ids
      getInventory(inventoryId).then(response => {
        this.form = response.data;
        this.ytInventoryHistoryList = response.data.ytInventoryHistoryList;
        this.open = true;
        this.title = "修改库存";
      });
    },
    //拿到对应的型号和单位
    getProductData(product){
       this.form.productModel = product.productModel;
       this.form.productUnit = product.productUnit;

      console.log('66666',product)




    },
    /** 出入库记录查看按钮操作 */
    handleInfo(row) {
      const inventoryId = row.inventoryId;
      this.$router.push("/inventory/inventory-info/history/" + inventoryId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.ytInventoryHistoryList = this.ytInventoryHistoryList;
          if (this.form.inventoryId != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryIds = row.inventoryId || this.ids;
      this.$modal.confirm('是否确认删除库存编号为"' + inventoryIds + '"的数据项？').then(function() {
        return delInventory(inventoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 出入库记录序号 */
    rowYtInventoryHistoryIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 复选框选中数据 */
    handleYtInventoryHistorySelectionChange(selection) {
      this.checkedYtInventoryHistory = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/inventory/export', {
        ...this.queryParams
      }, `库存信息_${new Date().getTime()}.xlsx`)
    },
    querySearchProduct(queryString, cb) {
      var brandsRestaurants = this.brandsRestaurants;
      var results = queryString ? brandsRestaurants.filter(this.createFilter(queryString)) : brandsRestaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 选择产品类型执行方法
    handleSelectProduct(item) {
      console.log("选择中的Product信息",item)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadAllProduct() {
      // 判断本地缓存是否有品牌数据
      if (localStorage.getItem('products') ) {
        return JSON.parse(localStorage.getItem('products'));
      } else {
        return [
          { "value": ""},
        ]
      }
    },
  },
  mounted() {
    this.productRestaurants = this.loadAllProduct();
  }
};
</script>
